// pages/time/index.js
let app = getApp()
import { socketId, setVjTime } from "../../api/score"
Page({
	data: {
		statusHeight: app.globalData.window.statusHeight || 1,
		navheight: app.globalData.window.navheight || 1,
		safetyArea: app.globalData.safetyArea + 16,
		time_m: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
		time_s: [],
		xz_time: [0, 0],
		circleData: {
			hanleTime: null,
			t: 0,
			gradientColor: {
				'0%': '#54A2FF',
				'100%': '#5854FF',
			},
			text: '00:00'
		},
		isShowTimeBox: false,
		socketIdData: '',
		id: null
	},
	onLoad(option) {
		this.setData({ id: Number(option.id) })
		socketId(option.id).then(res => {
			this.setData({ socketIdData: res.data.result })
		})
	},
	onShow() {
		this.setS()
	},
	setS() {
		for (let index = 0; index < 60; index++) {
		let time_s = JSON.parse(JSON.stringify(this.data.time_s))
			time_s.push(`${index}`)
			this.setData({ time_s })
		}
	},
	bindchange(e) {
		this.setData({ xz_time: e.detail.value })
	},
	submit() {
		let s_all = Number(this.data.time_m[this.data.xz_time[0]]) * 60 + Number(this.data.time_s[this.data.xz_time[1]]);
		if (s_all <= 0) {
			this.showError('时间需要大于0S')
			return false;
		}
		if(this.data.isShowTimeBox) {
			clearInterval(this.data.circleData.hanleTime)
			this.setData({
				circleData: {
					hanleTime: null,
					t: 0,
					gradientColor: {
						'0%': '#54A2FF',
						'100%': '#5854FF',
					},
					text: '00:00'
				},
				isShowTimeBox: false
			})
			return false;
		}
		this.setData({ isShowTimeBox: true })
		setVjTime({ timeInt: s_all, scoreProjectId: this.data.id })
		this.hanleTime(Number(this.data.time_m[this.data.xz_time[0]]), Number(this.data.time_s[this.data.xz_time[1]]), s_all)
	},
	showError(t, type = 'error') { //展示toast提醒
		wx.showToast({
			title: t,
			icon: type,
			duration: 2000
		})
	},
	hanleTime(m, s, s_all) {
		let s_new = s_all
		this.setData({
			'circleData.text': `${m <= 9 ? `0${m}`: m}:${s <= 9 ? `0${s}`: s}`,
			'circleData.hanleTime': setInterval(() => {
				s_new--;
				s--;
				let d = Math.ceil((s_all - s_new) / s_all * 100);
				this.setData({'circleData.t': d})
				if (s <= 0 && m == 0) {
					clearInterval(this.data.circleData.hanleTime)
				}
				if (s <= 0 && m > 0) {
					m-=1;
					s = 59;
				}
				this.setData({ 'circleData.text': `${m <= 9 ? `0${m}`: m}:${s <= 9 ? `0${s}`: s}` })
			}, 1000)
		})
	},
	goBack() {
		wx.navigateBack({
			delta: 1
		})
	},
})
